/**
 * Created by zlkmu on 2017/8/18.
 */
//辅助函数，处理单项复核窗口信息的显示或详情信息的显示
function initFuheItemDlg(item, preitem, disableInput){
    $('.input_fee').each(function(){
        $(this).next('span').html('');
        $(this).val(0);
        $(this).attr('disabled', disableInput);

    });

    if(self_drive == 1){
        $('.self_drive_fee').show();
        $('.non_self_drive').hide();
        $('.pre_fee').eq(0).val(preitem.oil_fee);
        $('.pre_fee').eq(1).val(preitem.pass_fee);
        $('.pre_fee').eq(2).val(preitem.distance);
        $('.pre_fee').eq(11).val(preitem.car_main_fee);

        $('.input_fee').eq(0).val(item.oil_fee);
        $('.input_fee').eq(1).val(item.pass_fee);
        $('.input_fee').eq(2).val(item.distance);
        $('.input_fee').eq(11).val(item.car_main_fee);
    }
    else{
        $('.self_drive_fee').hide();
        $('.non_self_drive').show();
        $('.pre_fee').eq(3).val(preitem.car_fee);
        $('.pre_fee').eq(4).val(preitem.boat_fee);
        $('.pre_fee').eq(5).val(preitem.flight_fee);

        $('.input_fee').eq(3).val(item.car_fee);
        $('.input_fee').eq(4).val(item.boat_fee);
        $('.input_fee').eq(5).val(item.flight_fee);
    }
    $('.pre_fee').eq(6).val(preitem.hotel_fee);
    $('.pre_fee').eq(7).val(preitem.food_fee);
    $('.pre_fee').eq(8).val(preitem.inci_fee);
    $('.pre_fee').eq(9).val(preitem.suspect_fee);
    $('.pre_fee').eq(10).val(preitem.reward_fee);
    $('.pre_fee').eq(12).val(preitem.other_fee);

    $('.input_fee').eq(6).val(item.hotel_fee);
    $('.input_fee').eq(7).val(item.food_fee);
    $('.input_fee').eq(8).val(item.inci_fee);
    $('.input_fee').eq(9).val(item.suspect_fee);
    $('.input_fee').eq(10).val(item.reward_fee);
    $('.input_fee').eq(12).val(item.other_fee);
}

//辅助函数，获取某条复核窗口的输入信息
function processFuheItemDataInput(){
    var input_fees = $('.input_fee');
    for(var i = 0; i < input_fees.length; i++){
        $(input_fees[i]).bind('input propertychange',function() {
            if($(this).next('span').hasClass('state'))
                $(this).next().remove();

            var input_value = $(this).val();
            var max_v = $(this).parent().next().next().find('input').val();
            if(input_value < -1 || !checkNum(input_value) || parseFloat(input_value) > parseFloat(max_v)) {
                $(this).after("<span class='state ui-state-error-text'>" +
                    "<i class='ui-icon ui-icon-circle-close'></i>" +
                    "</span>");
            }
            else{
                $(this).after("<span class='state'>" +
                    "<i class='ui-icon ui-icon-circle-check'></i>" +
                    "</span>");
            }
        });
    }
}

//辅助函数，计算复核报销数据
function calcFuheTotalMoney(){
    var total_car_fee = 0.0;
    var total_boat_fee = 0.0;
    var total_flight_fee = 0.0;

    var total_hotel_fee = 0;
    var total_food_fee = 0;
    var total_inci_fee = 0;
    var total_other_fee = 0;
    var total_distance = 0;
    var total_oil_fee = 0;
    var total_pass_fee = 0;

    var total_official_fee = 0;
    for(var i = 0; i < fuhe_data.data.length; i++){
        total_car_fee += parseFloat(fuhe_data.data[i].car_fee);
        total_boat_fee += parseFloat(fuhe_data.data[i].boat_fee);
        total_flight_fee += parseFloat(fuhe_data.data[i].flight_fee);

        total_hotel_fee += parseFloat(fuhe_data.data[i].hotel_fee);
        total_food_fee += parseFloat(fuhe_data.data[i].food_fee);
        total_inci_fee += parseFloat(fuhe_data.data[i].inci_fee);
        total_other_fee += parseFloat(fuhe_data.data[i].other_fee)
            + parseFloat(fuhe_data.data[i].suspect_fee)
            + parseFloat(fuhe_data.data[i].reward_fee)
            + parseFloat(fuhe_data.data[i].car_main_fee);
        total_distance += parseFloat(fuhe_data.data[i].distance);
        total_pass_fee += parseFloat(fuhe_data.data[i].pass_fee);
        total_oil_fee += parseFloat(fuhe_data.data[i].oil_fee);

        total_official_fee += parseFloat(fuhe_data.data[i].flight_fee) + parseFloat(fuhe_data.data[i].hotel_fee)
            + parseFloat(fuhe_data.data[i].car_main_fee) + parseFloat(fuhe_data.data[i].oil_fee);
    }
    $('.fuhe_total_row').remove();
    $('.fee_row').first().before(
        "<tr class='fuhe_total_row' style='background-color:#F5DEB3'>" +
        "<td class='td_right' colspan='5'>"+ '复核小计：' + "</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? total_car_fee.toFixed(2) : total_oil_fee.toFixed(2)) + "</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? total_boat_fee.toFixed(2) : total_pass_fee.toFixed(2)) +"</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? total_flight_fee.toFixed(2) : total_distance.toFixed(2)) + "</td>" +
        "<td class='td_center'></td>" +
        "<td class='td_center'>" + total_hotel_fee.toFixed(2) + "</td>" +
        "<td class='td_center'>" + total_food_fee.toFixed(2) + "</td>" +
        "<td class='td_center'>" + total_inci_fee.toFixed(2) + "</td>" +
        "<td class='td_center'>" + total_other_fee.toFixed(2) + "</td>" +
        "<td class='td_center'></td>" +
        "</tr>");

    //计算总金额
    var total_fuhe_fee = total_car_fee + total_boat_fee + total_oil_fee + total_pass_fee + total_flight_fee + total_hotel_fee
        + total_food_fee + total_inci_fee + total_other_fee;
    $('#fuhe_official_fee').html(total_official_fee.toFixed(2));
    $('#fuhe_total_fee').html(total_fuhe_fee.toFixed(2));

    fuhe_data.total_official_fee = total_official_fee.toFixed(2);
    fuhe_data.total_fuhe_fee = total_fuhe_fee.toFixed(2);
}

//辅助函数，创建某条复核报销数据信息
function createFuheItemData(id){
    var input_fees = $('.input_fee');
    for(var i = 0; i < input_fees.length; i++){
        if($(input_fees[i]).next('span').hasClass('ui-state-error-text')){
            return 0;
        }
    }
    //查看一下是否存在本条数据，这时候就修改数据
    for(var i = 0; i < fuhe_data.data.length; i++){
        if(fuhe_data.data[i].id == id){
            fuhe_data.data[i] = {
                'id': id,
                'start_time': curItem.fee_data_item[id].start_time,
                'start_addr': curItem.fee_data_item[id].start_dest,
                'start_county': curItem.fee_data_item[id].start_county,
                'end_time': curItem.fee_data_item[id].end_time,
                'end_addr': curItem.fee_data_item[id].end_dest,
                'end_county':curItem.fee_data_item[id].end_county,
                'stay_days':curItem.fee_data_item[id].stay_days,
                'road_days': curItem.fee_data_item[id].road_days,
                'oil_fee': parseFloat($(input_fees[0]).val()).toFixed(2),
                'pass_fee': parseFloat($(input_fees[1]).val()).toFixed(2),
                'distance' : parseFloat($(input_fees[2]).val()).toFixed(2),
                'car_fee' : parseFloat($(input_fees[3]).val()).toFixed(2),
                'boat_fee' : parseFloat($(input_fees[4]).val()).toFixed(2),
                'flight_fee' : parseFloat($(input_fees[5]).val()).toFixed(2),
                'hotel_fee' : parseFloat($(input_fees[6]).val()).toFixed(2),
                'food_fee' : parseFloat($(input_fees[7]).val()).toFixed(2),
                'inci_fee' : parseFloat($(input_fees[8]).val()).toFixed(2),
                'suspect_fee' : parseFloat($(input_fees[9]).val()).toFixed(2),
                'reward_fee' : parseFloat($(input_fees[10]).val()).toFixed(2),
                'car_main_fee' : parseFloat($(input_fees[11]).val()).toFixed(2),
                'other_fee' : parseFloat($(input_fees[12]).val()).toFixed(2)
            };
            return 1;
        }
    }
    fuhe_data.data.push({
        'id': id,
        'start_time': curItem.fee_data_item[id].start_time,
        'start_addr': curItem.fee_data_item[id].start_dest,
        'start_county': curItem.fee_data_item[id].start_county,
        'end_time': curItem.fee_data_item[id].end_time,
        'end_addr': curItem.fee_data_item[id].end_dest,
        'end_county':curItem.fee_data_item[id].end_county,
        'stay_days':curItem.fee_data_item[id].stay_days,
        'road_days': curItem.fee_data_item[id].road_days,
        'oil_fee': parseFloat($(input_fees[0]).val()).toFixed(2),
        'pass_fee': parseFloat($(input_fees[1]).val()).toFixed(2),
        'distance' : parseFloat($(input_fees[2]).val()).toFixed(2),
        'car_fee' : parseFloat($(input_fees[3]).val()).toFixed(2),
        'boat_fee' : parseFloat($(input_fees[4]).val()).toFixed(2),
        'flight_fee' : parseFloat($(input_fees[5]).val()).toFixed(2),
        'hotel_fee' : parseFloat($(input_fees[6]).val()).toFixed(2),
        'food_fee' : parseFloat($(input_fees[7]).val()).toFixed(2),
        'inci_fee' : parseFloat($(input_fees[8]).val()).toFixed(2),
        'suspect_fee' : parseFloat($(input_fees[9]).val()).toFixed(2),
        'reward_fee' : parseFloat($(input_fees[10]).val()).toFixed(2),
        'car_main_fee' : parseFloat($(input_fees[11]).val()).toFixed(2),
        'other_fee' : parseFloat($(input_fees[12]).val()).toFixed(2)
    });

    return 1;
}

//辅助函数，处理复核数据的显示
function showFuheItemInfo(id, oldColor){
    var fuhe_item = $('.apply_row').eq(id).next();
    if($(fuhe_item).hasClass('fuhe_row')){
        $(fuhe_item).remove();
    }
    var curdata = {};
    for(var i = 0; i < fuhe_data.data.length; i++){
        if(fuhe_data.data[i].id == id){
            curdata = fuhe_data.data[i];
            break;
        }
    }
    $('.apply_row').eq(id).css('background-color', oldColor);
    $('.apply_row').eq(id).after(
        "<tr class='fuhe_row'>" +
        "<td class='td_center'></td>" +
        "<td class='td_center'></td>" +
        "<td class='td_center'></td>" +
        "<td class='td_center'></td>" +
        "<td class='td_right'>复核数据：</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? curdata.car_fee : curdata.oil_fee) + "</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? curdata.boat_fee : curdata.pass_fee) +"</td>" +
        "<td class='td_center'>" + (self_drive == 0 ? curdata.plane_fee : curdata.distance) + "</td>" +
        "<td class='td_center'></td>" +
        "<td class='td_center'>" + curdata.hotel_fee + "</td>" +
        "<td class='td_center'>" + curdata.food_fee + "</td>" +
        "<td class='td_center'>" + curdata.inci_fee + "</td>" +
        "<td class='td_center'>" + (parseFloat(curdata.suspect_fee)
        + parseFloat(curdata.other_fee)
        + parseFloat(curdata.reward_fee)
        + parseFloat(curdata.car_main_fee)).toFixed(2) + "</td>" +
        "<td class='td_center'></td>" +
        "</tr>"
    );
    $('.fuhe_row').each(function(index, elem){
        $(this).css('background-color', fuhed_item_color);
    })
}

//辅助函数，处理某条报销数据信息的复核
function fuheItem(id){
    var title = '报销核销窗口-' + '报销信息' + (id + 1);
    var curFeeData = curItem.fee_data_item[id];
    var preFeeData = curItem.fee_data_item[id];
    //如果填写过复核数据，就用复核数据条目
    for(var i = 0; i < fuhe_data.data.length; i++){
        if(fuhe_data.data[i].id == id){
            curFeeData = fuhe_data.data[i];
            preFeeData = curItem.fee_data_item[id];
            break;
        }
    }
    //否则使用原始报销数据
    initFuheItemDlg(curFeeData, preFeeData, false);



    var oldColor = $('.apply_row').eq(id).css('background-color');
    $('.apply_row').eq(id).css('background-color', fuheing_item_color);
    $('#check_dlg').dialog({
        resizable: false,
        height: "auto",
        width: "auto",
        modal: true,
        title: title,
        buttons:{
            '确定': function(){
                if(createFuheItemData(id) == 1) {
                    showFuheItemInfo(id, oldColor);
                    calcFuheTotalMoney();
                    $(this).dialog('close');
                }
                else{
                    $.prompt("<h3>数据填写格式错误或超过预报销费用</h3>", {
                        title: '错误提醒',
                        buttons: {'确定': true}
                    })
                }
            }
        }

    })

}

//辅助函数，处理复核状态下复核按钮按下后的处理
function processFuhePress(){
    $('.fee_confirm').click(function(e){
        e.preventDefault();
        var id = $(this).parent().parent().find('td').eq(0).html();

        if($(this).hasClass('fee_item')){
            fuheItem(id-1);
        }
    })

}

//辅助函数，获取部门
function getSection(){
    $('#section_type').empty();

    $.get(url + 'Common/GetSection.php', function(result){
        var t = JSON.parse(result);

        for(var i = 0; i < t.length; i++){
            var id = t[i]['section_id'];
            var name = t[i]['section_name'];
            $('#section_type').append("<option value='"+id+"'>" + name + "</option>");
        }

    })
}

//辅助函数，处理最终核销处理对话框
function initFinalFuheCheckDlg(){
    $('#f_c_check_total_fee').val(fuhe_data.total_fuhe_fee);
    $('#f_c_pre_total_fee').val(curItem.fee_data.pre_total_fee);
    if(curItem.travel_app_data.is_loan_money == 1){
        $('#f_c_loan_fee').attr('disabled', false);
        $('#f_c_loan_pre_fee').val(curItem.travel_app_data.loan_money.money);
        fuhe_data.loan_fee_id = curItem.travel_app_data.loan_money.loan_money_id;

    }
    else{
        $('#f_c_loan_fee').attr('disabled', true);
        fuhe_data.loan_fee_id = '';
    }
    $('#f_c_official_pre_fee').val(fuhe_data.total_official_fee);
//        $("#section_type").find("option[text='" + curItem.travel_app_data.section_name + "']").attr("selected",true);

    $("#section_type").find("option[value=" + curItem.travel_app_data.section_ID + "]").attr("selected",true);

}
//辅助函数,判断数据输入是否合法
function isValidInput(inputElem, maxVal){
    if($(inputElem).next('span').hasClass('state'))
        $(inputElem).next().remove();
    var v1 = $(inputElem).val();

    if( (parseFloat(v1) > parseFloat(maxVal)) || !checkNum(v1)){
        $(inputElem).after("<span class='state ui-state-error-text'>" +
            "<i class='ui-icon ui-icon-circle-close'></i>" +
            "</span>");
        return false;
    }
    else{
        $(inputElem).after("<span class='state'>" +
            "<i class='ui-icon ui-icon-circle-check'></i>" +
            "</span>");
        return v1;
    }
}

//辅助函数，处理最终核销对话框数据的输入
function getFinalFuheData(){
    if(! (v = isValidInput($('#f_c_loan_fee'), $('#f_c_loan_pre_fee').val()))){
        return false;
    }
    fuhe_data.check_loan_fee = v;

    if(!(v = isValidInput($('#f_c_check_official_fee'), $('#f_c_official_pre_fee').val()))){
        return false;
    }
    fuhe_data.official_fee = v;

    if(!(v = isValidInput($('#section_fee'), fuhe_data.total_fuhe_fee))){
        return false;
    }
    fuhe_data.section_fee = v;

    fuhe_data.section_id = $('#section_type').val();

    return true;

}
//辅助函数，财务核销处理
function processFeeCheck(){
    $('#dataLoad').show();
    $.post(url + 'BusinessFee/FinanceCheckBusinessFee.php', fuhe_data, function(data){
        $('#dataLoad').hide();
        var t = JSON.parse(data);
        if(t.state == 1){
            $.prompt("<h3>报销信息复核成功</h3>", {
                title: '操作提醒',
                buttons: {'确定': true},
                submit: function (e, v, m, f) {
                    if(v){
                        //打印报销单
                        printBusinessFeePDF();
                    }
                    else{
                        jumpPage('finance_fee_approve.html');
                    }
                }
            });
        }
        else{
            $.prompt("<h3>网络或数据库故障，请稍后再试</h3>", {
                title: '错误提醒',
                buttons: {'确定': true}
            });
        }
    })
}

//辅助函数，复核成功后的PDF打印功能
function printBusinessFeePDF(){
    $.prompt("<h3>自动生成报销单</h3>", {
        title: '操作提醒',
        buttons: {'确定': true},
        submit: function (e, v, m, f) {
            if(v){
                $('#dataLoad').show();
                $.post(url + 'PDF/CreateBusinessFeePDF.php', {'approval_id':fuhe_data.travel_fee_id}, function(data){
                    var t= JSON.parse(data);
                    $('#dataLoad').hide();
                    if(t.state == 1){
                        window.open(url + t.url);
                        jumpPage('finance_fee_approve.html');
                    }
                    else{
                        $.prompt("<h3>生成失败，请稍后在打印报销单功能中尝试</h3>", {
                            title: '错误提醒',
                            buttons: {'确定': true},
                            submit: function(e, v, m, f){
                                if(v){
                                    jumpPage('finance_fee_approve.html');
                                }
                            }
                        })
                    }
                });
            }
        }
    });
}

//辅助函数，最终核销处理
function finalCheckFee(){
    $('#check_btn').click(function(){

        if(fuhe_data.data.length == curItem.fee_data_item.length){
            initFinalFuheCheckDlg();
            $('#final_check_dlg').dialog({
                resizable: false,
                height: "auto",
                width: "auto",
                modal: true,
                buttons:{
                    '确定': function(){
                        if(getFinalFuheData()){
                            processFeeCheck();
                            $(this).dialog('close');
                        }
                        else{
                            $.prompt("<h3>数据填写错误，请根据提示修改</h3>", {
                                title: '错误提醒',
                                buttons: {'确定': true}
                            })
                        }
                    },
                    '取消':function(){
                        $(this).dialog('close');
                    }
                }
            })
        }
        else{
            $.prompt("<h3>尚有未复核的报销数据，请核销</h3>", {
                title: '错误提醒',
                buttons: {'确定': true}
            })
        }
    })
}